package tk.ovzs.starcraftRanker;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.jsoup.nodes.Document;

import tk.ovzs.DataModels.UserProfile;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.format.Time;
import android.util.Log;
import android.widget.RemoteViews;

public class StarcraftRankerProvider extends AppWidgetProvider
{	
	public static final String ACTION_WIDGET_CONTROL = "android.appwidget.action.APPWIDGET_CONFIGURE";
	
	private Document docum;
	private UserProfile userProfile;
	
	private Handler messageHandler = new Handler() {

		public void handleMessage(Message msg) 
		{			
			Log.d("misc", "received message: " + msg);

//			if (msg.get == 0)
//			{
//				WebPageScraper.parseDocument(docum);
				userProfile = UserProfile.getInstance();
//				showWidget();
//				}
//			}

			super.handleMessage(msg);	
		}
	};
	
	 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	 {
		 Log.d("misc", "onUpdate");
	        final int N = appWidgetIds.length;
	        
	        // Perform this loop procedure for each App Widget that belongs to this provider
	        for (int i=0; i<N; i++)
	        {
	            int appWidgetId = appWidgetIds[i];

	            // Create an Intent to launch ExampleActivity
	            Intent configIntent = new Intent(context, StarcraftRankerConfigurator.class);
	            configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
	            configIntent.setAction(ACTION_WIDGET_CONTROL);
//	            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
	            
	            
	            Intent active = new Intent();
	            active.setAction("Action");
	            active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
//	            Uri data = Uri.withAppendedPath(Uri.parse(URI_SCHEME + "://widget/id/#"+command), String.valueOf(appWidgetId));
//	            active.setData(data);
	            
	                       
	            PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, PendingIntent.FLAG_ONE_SHOT);
	            PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
//	            remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
//	            remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent);

	            // Get the layout for the App Widget and attach an on-click listener
	            // to the button
	            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.starcraft_ranker_layout);
//	            views.setOnClickPendingIntent(R.id.button, pendingIntent);	 
	            
	            userProfile = UserProfile.getInstance();
				views.setTextViewText(R.id.playerName, "User2: " + userProfile.getUserName());
				views.setTextViewText(R.id.playerLeague, "League2: " + userProfile.getUserDivision1());
				views.setTextViewText(R.id.playerRank, "Rank2: " + String.valueOf(userProfile.getUserRank1()));
				Time now = new Time();
				now.setToNow();
				SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yy HH:MM:SS");
//	            views.setTextViewText(R.id.lastUpdate, new SimpleDateFormat().format(new Date()));
				views.setTextViewText(R.id.lastUpdate, sdf.format(now));
	            views.setOnClickPendingIntent(R.id.configureButton, configPendingIntent);	
	            views.setOnClickPendingIntent(R.id.refreshButton, actionPendingIntent);
//	            setAlarm(context.getApplicationContext(), appWidgetId, 50);
	            
	            // Tell the AppWidgetManager to perform an update on the current app widget
	            appWidgetManager.updateAppWidget(appWidgetId, views);
	        }
	        	       
	    }
	 
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		// TODO Auto-generated method stub
		for (int appWidgetId : appWidgetIds)
		{
			setAlarm(context, appWidgetId, -1);
		}
		super.onDeleted(context, appWidgetIds);
	}

	@Override
	public void onDisabled(Context context) {
		// TODO Auto-generated method stub
		Log.d("misc", "onDisable");
		super.onDisabled(context);
	}

	@Override
	public void onEnabled(Context context) {
		// TODO Auto-generated method stub
		Log.d("misc", "onEnable");
		super.onEnabled(context);			
	}

	@Override
	public void onReceive(Context context, Intent intent)
	{
		Log.d("misc", "onReceive: " + intent.getAction());
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(intent.getAction())) {
			final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
				this.onDeleted(context, new int[] { appWidgetId });
			}
		}
		else
		if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE))			
		{
//			docum = null;
//			//					docum = (Document) Jsoup.parse(url, 9000);
//			new Thread() {			
//				
//				public void run() {
//					try 
//					{							
//						URL url = new URL(userProfile.getUserProfileURL());
//						docum = (Document) Jsoup.parse(url, 9000);
//						if (docum != null)
//						{
//							messageHandler.sendEmptyMessage(0);
//						}
//						else
//						{
//							messageHandler.sendEmptyMessage(1);
//						}
//					}
//					catch (IOException e)
//					{
//						messageHandler.sendEmptyMessage(1);
//					}
//				}
//			}.start();
//			Log.d("misc", "thread in provider");
		}
		else 
			if (intent.getAction().equals("Action"))
			{
				Log.d("misc","received button event !!!");
			}
		super.onReceive(context, intent);
		
	} 
	
	private void setAlarm(Context context, int appWidgetId, int updateRateSeconds)
	{
        Intent widgetUpdate = new Intent();
        widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });

        // make this pending intent unique by adding a scheme to it
//        widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(ImagesWidgetProvider.URI_SCHEME + "://widget/id/"), String.valueOf(appWidgetId)));
        PendingIntent newPending = PendingIntent.getBroadcast(context, 0, widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);

        // schedule the updating
        AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (updateRateSeconds >= 0)
        {
            alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), updateRateSeconds * 1000, newPending);
        }
        else
        {
            alarms.cancel(newPending);
        }
    }
}